package de.zainodis.authorlist.ui;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import de.zainodis.authorlist.R;
import de.zainodis.authorlist.core.Application;
import de.zainodis.authorlist.model.AuthorLibraryComponent;
import de.zainodis.authorlist.model.AuthorsCreation;
import de.zainodis.authorlist.model.parsing.BookParser;
import de.zainodis.authorlist.model.parsing.CDParser;
import de.zainodis.commons.utils.Toaster;

/**
 * Displays CDs and Books recorded/written by the selected author.
 * 
 * @author fzarrai
 * 
 */
public class AuthorsCreationListFragment extends ListDownloadBaseFragment {

   public static final String TAG = "AuthorsCreationListFragment";
   public static final String AUTHOR_NAME = "author";

   private AuthorsCreationAdapter listAdapter;
   private int tasksCompleted = 0;

   @Override
   public void onActivityCreated(Bundle savedInstanceState) {
	 super.onActivityCreated(savedInstanceState);

	 String author = getArguments().getString(AUTHOR_NAME);

	 listAdapter = new AuthorsCreationAdapter(getActivity(), author);
	 setListAdapter(listAdapter);

   }

   @Override
   public void onResume() {
	 super.onResume();

	 AuthorLibraryComponent library = Application.getComponent(AuthorLibraryComponent.class);

	 if (library.get(listAdapter.getAuthor()).size() == 0) {
	    if (internetAvailable(true)) {
		  // No data available for this author, parse it from the internet
		  setListShown(false);
		  BooksDownloadTask task = new BooksDownloadTask();
		  task.execute();
		  CDsDownloadTask taskTwo = new CDsDownloadTask();
		  taskTwo.execute();

	    }
	 }
   }

   private class BooksDownloadTask extends XmlDownloadTask<String> {

	 @Override
	 protected void parse(InputStream stream) throws XmlPullParserException, IOException {
	    new BookParser().parse(stream);
	 }

	 @Override
	 protected String getUrl() {
	    return Application.getStringFromResId(R.string.books_url);
	 }

	 @Override
	 protected void onPostExecute(Void result) {
	    tasksCompleted++;
	    onTasksCompleted();
	 }

	 @Override
	 protected String getTag() {
	    return "BooksDownloadTask";
	 }

   }

   private class CDsDownloadTask extends XmlDownloadTask<String> {

	 @Override
	 protected void parse(InputStream stream) throws XmlPullParserException, IOException {
	    new CDParser().parse(stream);
	 }

	 @Override
	 protected void onPostExecute(Void result) {
	    tasksCompleted++;
	    onTasksCompleted();
	 }

	 @Override
	 protected String getUrl() {
	    return Application.getStringFromResId(R.string.cds_url);
	 }

	 @Override
	 protected String getTag() {
	    return "CDsDownloadTask";
	 }

   }

   protected void onTasksCompleted() {
	 if (tasksCompleted == 2) {
	    // We're done loading items, show the list
	    tasksCompleted = 0;
	    listAdapter.onUpdate();
	    listAdapter.notifyDataSetChanged();
	    setListShown(true);
	 }
   }

   private class AuthorsCreationAdapter extends BaseAdapter {

	 private final String author;
	 private ArrayList<AuthorsCreation> entries;
	 private LayoutInflater layoutInflater;

	 public AuthorsCreationAdapter(Context context, String author) {
	    this.author = author;
	    this.layoutInflater = (LayoutInflater) context
			.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    onUpdate();
	 }

	 public String getAuthor() {
	    return author;
	 }

	 @Override
	 public int getCount() {
	    return entries.size();
	 }

	 @Override
	 public boolean isEnabled(int position) {
	    // Makes list items un-selecteable
	    return false;
	 }

	 @Override
	 public Object getItem(int position) {
	    return entries.get(position);
	 }

	 @Override
	 public long getItemId(int position) {
	    return position;
	 }

	 @Override
	 public View getView(int position, View convertView, ViewGroup parent) {
	    View view = convertView;
	    if (convertView == null) {
		  view = layoutInflater.inflate(R.layout.listitem_authorscreation, null);
	    }

	    AuthorsCreation entry = entries.get(position);

	    ImageView image = (ImageView) view.findViewById(R.id.item_image);
	    image.setImageDrawable(getResources().getDrawable(entry.getIcon()));

	    TextView field = (TextView) view.findViewById(R.id.item_title);
	    field.setText(entry.getTitle());

	    field = (TextView) view.findViewById(R.id.item_isbn);
	    String isbn = entry.getIsbn();
	    if (isbn == null) {
		  // If no isbn is available, we simply don't show the view
		  field.setVisibility(View.GONE);
	    } else {
		  field.setText(isbn);
		  field.setVisibility(View.VISIBLE);
	    }

	    field = (TextView) view.findViewById(R.id.item_price);
	    field.setText(entry.getPrice());

	    return view;
	 }

	 public void onUpdate() {
	    AuthorLibraryComponent library = Application.getComponent(AuthorLibraryComponent.class);
	    entries = new ArrayList<AuthorsCreation>(library.get(author));

	 }
   }
}
